import BaseController from '../../core/baseController';
import { getCurrentStimp } from '../../utils/index';


export default class MarketController extends BaseController {
  constructor(ctx) {
    super(ctx)
    this.service = ctx.service.wx.cart;
    this.modelPrefix = 'cart';
  }

  async list() {
    const { user_id } = this.ctx.validateReq(
      `${this.modelPrefix}.list`,
    ).query;

    const where = { user_id };
    const result = await this.service.list(where);

    if (result) {
      this.ctx.success({
        data: result
      });
    }
  }

  async create() {
    const { body } = this.ctx.validateReq(`${this.modelPrefix}.create`);

    const { user_id, number, goods_id } = body;

    //删除
    if (number === 0) {
      await this.service.model.destroy(
        {
          where: {
            goods_id,
            user_id
          }
        }
      );
      return this.ctx.success();
    }

    const ans = await this.service.model.findOne({
      where: { user_id, goods_id }
    });
    const stemp = getCurrentStimp();
    Object.assign(body, {
      update_at: stemp,
    });

    let result: any = null;
    // 存在，修改number
    if (ans) {
      result = await this.service.update(ans.id, { number })
    } else {
      Object.assign(body, { create_at: stemp });
      result = await this.service.create(body);
    }


    if (result) {
      this.ctx.success({
        data: result,
        status: 201,
      });
    }
  }

  // 删除
  async clear() {
    const { params: { user_id } } = this.ctx.validateReq(`${this.modelPrefix}.clear`);
    const result = await this.service.clear(user_id);
    if (result) {
      this.ctx.success({
        data: {
          id: result.id,
        }
      });
    }
  }

}
